import pkg from '../../../package.json';
import fetch from 'fermionjs/lib/fetch';
import errorCodesBuilder from '../helpers/errorCodesBuilder';
import FormData from 'form-data';
const { name } = pkg;

const errorCodes = errorCodesBuilder();
export default function templateEmails(to, subject, tempId, option) {
	const {
		log,
		app: {
			config: {
				[name]: { sendEmailInfo },
			},
		},
	} = this;
	if (!to.length) return;
	const data = {
		apiUser: sendEmailInfo.apiUser,
		apiKey: sendEmailInfo.apiKey,
		from: sendEmailInfo.from,
		xsmtpapi: {
			to: to,
			sub: option,
		},
		subject: subject,
		templateInvokeName: tempId,
	};
	if (data.xsmtpapi.to.length > 100) {
		const splitArr = dealBatchData(data);
		return Promise.all(splitArr.map(fetchEmail));
	} else {
		return fetchEmail(log, data);
	}
}
function dealBatchData(data) {
	const { xsmtpapi } = data;
	const newData = [];
	const toLen = xsmtpapi.to.length;
	const page = Math.ceil(toLen / 100);
	const dataObj = Object.assign({}, data);
	for (let i = 0; i < page; i++) {
		dataObj.xsmtpapi.to = xsmtpapi.to.slice(i * 100, (i + 1) * 100);
		dataObj.xsmtpapi.sub['%user%'] = xsmtpapi.sub['%user%'].slice(
			i * 100,
			(i + 1) * 100
		);
		dataObj.xsmtpapi.sub['%version%'] = xsmtpapi.sub['%version%'].slice(
			i * 100,
			(i + 1) * 100
		);
		if (xsmtpapi.sub['%time%']) {
			dataObj.xsmtpapi.sub['%time%'] = xsmtpapi.sub['%time%'].slice(
				i * 100,
				(i + 1) * 100
			);
		}
		newData.push(dataObj);
	}
	return newData;
}
function fetchEmail(log, data) {
	const formData = new FormData();
	Object.keys(data).map(key => {
		formData.append(
			key,
			typeof data[key] === 'object' ? JSON.stringify(data[key]) : data[key]
		);
	});
	return fetch('https://api.sendcloud.net/apiv2/mail/sendtemplate', {
		method: 'POST',
		body: formData,
	})
		.then(res => {
			if (!res.result) {
				log.error({ res }, '邮件发送：邮件发送失败');
				throw new Error(res.message);
			}
		})
		.catch(err => {
			const error = errorCodes['[0E]邮件发送：邮件发送失败'].from(err);
			log.error(
				{
					error,
				},
				error.rawMessage
			);
			throw error;
		});
}
